package com.tianji.promotion.lock.strategy;

import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.promotion.lock.LockFactory;
import com.tianji.promotion.lock.MyLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class FailAfterTimeoutStrategy implements LockStategy{


    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private LockFactory lockFactory;

    @Override
    public boolean lock(MyLock myLock)throws Exception {
        RLock lock = lockFactory.getLock(myLock.lockType(), myLock.name());
        boolean locked = lock.tryLock(myLock.waitTime(), myLock.leaseTime(), myLock.timeUnit());
        if(!locked){
            throw new BizIllegalException("获取锁失败");
        }
        return locked;
    }

    @Override
    public void unlock(MyLock myLock) {
        RLock lock = lockFactory.getLock(myLock.lockType(), myLock.name());
        lock.unlock();
    }
}
